package com.javatest.springboot2ratelimit.aop;

import com.javatest.springboot2ratelimit.annoation.MakeRateLimit;
import javax.servlet.http.HttpServletRequest;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

/**
 * Created with IntelliJ IDEA.
 * Description:
 *
 * @author lzy
 * @create 2020-07-22 下午2:47
 */
public abstract class AbstractRateLimitAspect {
    private static final String UNKNOWN = "unknown";

    @Pointcut("execution(public * com.javatest.springboot2ratelimit.controller..*.*(..))")
    public void limitPointCut() {
    }

    /**
     * Before.
     *
     * @param joinPoint the join point
     * @param rateLimit the rate limit
     */
    public abstract void before(JoinPoint joinPoint, MakeRateLimit rateLimit);

    public String getIpAddress() {
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        String ip = request.getHeader("x-forwarded-for");
        if (ip == null || ip.length() == 0 || UNKNOWN.equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || UNKNOWN.equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || UNKNOWN.equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        return ip;
    }
}
